package engine.services.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import engine.services.IHttpConnectionService;


public class HttpConnectionService implements IHttpConnectionService {
	private Log log = LogFactory.getLog(HttpConnectionService.class);

	Proxy proxy = null;
	InetSocketAddress HTTPProxyAddress = null;

	private HttpConnectionService() {
		
	}
	
	public void setHTTPProxyAddress(InetSocketAddress hTTPProxyAddress) {
		HTTPProxyAddress = hTTPProxyAddress;
		proxy = new Proxy(Type.HTTP, hTTPProxyAddress);
	}

	
	/* (non-Javadoc)
	 * @see engine.beans.impl.IHttpConnectionService#openConnection(java.lang.String)
	 */
	public HttpURLConnection openConnection(String urlStr)
		throws Exception {
		HttpURLConnection conn = getConnection(urlStr);
		
		conn.setRequestMethod("GET");
		conn.setAllowUserInteraction(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		int code = conn.getResponseCode();
		if (code != 200) {
			log.warn("invalid response. url: "+urlStr+", response code: " + code);
			throw new RuntimeException("invalid URL");
		}
		return conn;
	}
	

	/* (non-Javadoc)
	 * @see engine.beans.impl.IHttpConnectionService#closeConnection(java.net.HttpURLConnection)
	 */
	public void closeConnection(HttpURLConnection conn) throws IOException {		
		conn.getInputStream().close();
		conn.disconnect();
	}
	
	/* (non-Javadoc)
	 * @see engine.beans.impl.IHttpConnectionService#getUrlContentString(java.net.HttpURLConnection)
	 */
	public String getUrlContentString(HttpURLConnection conn) throws Exception {
		String urlContentStr = "";
		String line;
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		while ((line = in.readLine()) != null) {
			urlContentStr += line;
		}
		in.close();
		closeConnection(conn);
		return urlContentStr;
	}
	
	private HttpURLConnection getConnection(String urlStr) throws Exception{
		URL url = new URL(urlStr);
		HttpURLConnection conn = null;
		if (log.isDebugEnabled()) {
			log.debug("making request for: " + urlStr);			
		}
		if (proxy == null) {
			conn =(HttpURLConnection) url.openConnection();
		} else {
			conn =(HttpURLConnection) url.openConnection(proxy);
			
		}
		return conn;
	}
	
	
	/* (non-Javadoc)
	 * @see engine.beans.impl.IHttpConnectionService#saveURLContentAsFile(java.lang.String, java.lang.String)
	 */
	public InputStream getURLContentForStream(String urlStr) throws Exception {
		HttpURLConnection conn = getConnection(urlStr);
        return conn.getInputStream();
        
	}
}
